﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MethodWorx.CMS.Plugins;
using System.Web.Mvc;
using MethodWorx.CMS.Membership;

namespace MethodWorx.CMS.UI.Areas.Dashboard.Models
{
    public class DashboardModel
    {
        private IPluginRepository plugins;
        private User user;

        public DashboardModel(User user, IPluginRepository plugins)
        {
            this.plugins = plugins;
            this.user = user;
        }

        public bool DialogMode { get; private set; }

        public SelectList GetPluginsSelectList()
        {
            return new SelectList(
                plugins.All().OfType<SafePlugin>().Where(p => p.IsSafe && p.Is<IDashboardPlugin>()), "Id", "Name");
        }

        public IEnumerable<DashboardWidget> GetWidgets(int columnIndex)
        {
            foreach (var dw in user.DashboardWidgets.Where(dw => dw.ColumnIndex == columnIndex).OrderBy(dw => dw.Sequence))
            {
                var plugin = plugins.All().OfType<SafePlugin>().Where(p => p.IsSafe == true && p.Id == dw.PluginId).FirstOrDefault();
                if(plugin != null)
                {
                    var widgets = plugin.Invoke<IDashboardPlugin, IEnumerable<DashboardWidget>>(p => p.GetWidgets());
                    var widget = widgets.Where(w => w.Id == dw.WidgetId).FirstOrDefault();
                    if (widget != null)
                        yield return widget;
                }
            }
        }
    }
}